package com.china.produce.thread;


import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2022/7/21
 */
@Slf4j
public class ThreadPoolHelper {

    // 线程池大小
    private static final int POOL_SIZE = 40;

    private static ThreadPoolExecutor commitTaskPool = (ThreadPoolExecutor) new ScheduledThreadPoolExecutor(POOL_SIZE);

    public static void main(String[] args) throws InterruptedException {
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("test1", "123");
        map1.put("test2", "1234");
        ConcurrentHashMap<String, Object> map2 = new ConcurrentHashMap<>(16);
        map2.put("123", "456");

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map1.put("test3", "567");
        }).start();
        map1.put("test4", "99");
        TimeUnit.SECONDS.sleep(1);

        map1.entrySet().forEach(item -> {
            System.out.println("key : " + item.getKey() + " value : " + item.getValue());
        });
        TimeUnit.SECONDS.sleep(10);


        log.debug("shutdown commitTaskPool...");
        try {
            if (!commitTaskPool.isTerminated()) {
                log.debug("直接关闭失败[" + commitTaskPool.toString() + "]");
                commitTaskPool.awaitTermination(3, TimeUnit.SECONDS);
                if (commitTaskPool.isTerminated()) {
                    log.debug("成功关闭1[" + commitTaskPool.toString() + "]");
                } else {
                    log.debug("[" + commitTaskPool.toString() + "]关闭失败，执行shutdownNow...");
                    if (commitTaskPool.shutdownNow().size() > 0) {
                        log.debug("[" + commitTaskPool.toString() + "]没有关闭成功");
                    } else {
                        log.debug("shutdownNow执行完毕，成功关闭[" + commitTaskPool.toString() + "]");
                    }
                }
            } else {
                log.debug("成功关闭2[" + commitTaskPool.toString() + "]");
            }
        } catch (InterruptedException e) {
            log.warn("接收到中断请" + commitTaskPool.toString() + "停止操作");
        }

        ThreadLocal<String> tl = new ThreadLocal<>();
        tl.set("12345");
        tl.get();

    }



}
